package user

import (
	"beegoProject06/models/user"
	"beegoProject06/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"math"
	"net/http"
	"strconv"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) List() {

	o := orm.NewOrm()
	qs := o.QueryTable("sys_user")
	users := []user.User{}

	// 每页显示数据-4条 (pagePerNum)
	pagePerNum := 4

	// 总数据量
	count, _ := qs.Filter("is_delete", 0).Count()

	// 总页数 (count) =  总数据量 / 每页数据量   注：需要转换成int类型
	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))

	// 当前页 (currentPage)
	currentPage, err := c.GetInt("page")

	// err 当点击页面时候没有获取到当前页也就是null，所以默认显示第一页
	if err != nil {
		currentPage = 1
	}

	offsetNum := pagePerNum * (currentPage - 1)

	qs.Filter("is_delete", 0).Limit(pagePerNum).Offset(offsetNum).All(&users)

	// 判断上一页
	prePage := 1
	if currentPage == 1 {
		prePage = currentPage
	} else if currentPage > 1 {
		// 上一页
		prePage = currentPage - 1
	}

	// 下一页
	nextPage := 1
	// 如果当前页小于总页数
	if currentPage < countPage {
		// 下一页 就等于 当前页+1
		nextPage = currentPage + 1
		// 如果当前页面大于等于总页数
	} else if currentPage >= countPage {
		// 下一页 就等于 当前页
		nextPage = currentPage
	}

	// 引用倒入到函数page.go
	page_map := utils.Paginator(currentPage, pagePerNum, count)
	c.Data["page_map"] = page_map

	c.Data["users"] = users
	c.Data["prePage"] = prePage         /* 上一页*/
	c.Data["nextPage"] = nextPage       /* 下一页 */
	c.Data["currentPage"] = currentPage /* 当前页 */
	c.Data["countPage"] = countPage
	c.Data["count"] = count

	c.TplName = "user/user-list.html"
}

func (c *UserController) ToAdd() {
	c.TplName = "user/user-add.html"
}

func (c *UserController) DoAdd() {
	/* 获取前端数据 */
	username := c.GetString("username")
	password := c.GetString("password")
	age, _ := c.GetInt("age")
	gender, _ := c.GetInt("gender")
	phone := c.GetString("phone")
	addr := c.GetString("addr")
	isActive, _ := c.GetInt("is_active")

	/* 密码转换 */
	new_password := utils.Md5Text(password)

	/* phone转换int64 */
	phone_int64, _ := strconv.ParseInt(phone, 10, 64)

	/* 初始化数据库 */

	o := orm.NewOrm()
	user_data := user.User{
		UserName: username,
		Password: new_password,
		Age:      age,
		Gender:   gender,
		Phone:    phone_int64,
		Addr:     addr,
		IsActive: isActive,
	}

	/* 返回到前端ajax到数据 */
	messageMap := map[string]interface{}{}

	/* 数据库插入数据 */
	_, err := o.Insert(&user_data)
	if err != nil {
		fmt.Println(err)
		messageMap["code"] = 10001
		messageMap["msg"] = "添加数据出错,请重新添加!"
		c.Data["json"] = messageMap
	} else {
		messageMap["code"] = 200
		messageMap["msg"] = "添加成功!"
		c.Data["json"] = messageMap
	}

	c.ServeJSON()
}

func (c *UserController) IsActive() {
	// 获取数据
	is_active, _ := c.GetInt("is_active_val")
	id, _ := c.GetInt("id")

	// 初始化数据库
	o := orm.NewOrm()
	qs := o.QueryTable("sys_user").Filter("id", id)

	// 初始化返回数据
	messageMap := map[string]interface{}{}

	// 判断isActive，使用qs.Update更新
	if is_active == 1 {
		qs.Update(orm.Params{
			"is_active": 0,
		})
		messageMap["msg"] = "停用成功!"
	} else if is_active == 0 {
		qs.Update(orm.Params{
			"is_active": 1,
		})
		messageMap["msg"] = "启用成功!"
	}
	c.Data["json"] = messageMap
	c.ServeJSON()
}

func (c *UserController) Delete() {
	id, _ := c.GetInt("id")

	o := orm.NewOrm()
	o.QueryTable("sys_user").Filter("id", id).Update(orm.Params{
		"is_delete": 1,
	})
	c.Redirect(beego.URLFor("UserController.List"), http.StatusFound)
}

func (c *UserController) ResetPassword() {
	id, _ := c.GetInt("id")

	newPwd := utils.Md5Text("123456")

	o := orm.NewOrm()
	o.QueryTable("sys_user").Filter("id", id).Update(orm.Params{
		"password": newPwd,
	})
	c.Redirect(beego.URLFor("UserController.List"), http.StatusFound)
}

func (c *UserController) ToUpdate() {

	// 获取前端数据
	id, _ := c.GetInt("id")
	o := orm.NewOrm()
	userData := user.User{}
	o.QueryTable("sys_user").Filter("id", id).One(&userData)

	c.Data["user"] = userData

	c.TplName = "user/user-edit.html"
}
